package com.gxa.hualian.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 响应工具: 封装给前端响应操作
 * @author bill
 * @date 2022/5/6 15:39
 */
public class ResponseUtil {

    /**
     * 声明 response成员变量
     */
    private HttpServletResponse response ;
    /**
     * 声明 writer打印输出流对象
     */
    private PrintWriter writer ;
    /**
     * 声明 自定义的处理数据为Map的工具类对象
     */
    private JsonResult jsonResult;
    /**
     * 声明 jackson的转换器对象
     */
    private ObjectMapper objectMapper = new ObjectMapper();


    /**
     * 在构造方法中传参, 参数来自Servlet
     * @param response
     * @param jsonResult
     * @throws IOException
     */
    public ResponseUtil(HttpServletResponse response,JsonResult jsonResult) throws IOException {
        this.response = response;
        this.jsonResult = jsonResult;
        writer = response.getWriter();
    }

    /**
     * 实现给前端输出json的操作
     * @throws JsonProcessingException
     */
    public  void write() throws JsonProcessingException {
        // 把Map对象转换为json字符串
        String  jsonString = objectMapper.writeValueAsString(jsonResult.getMap());
        writer.println(jsonString);
        writer.flush();
        writer.close();
    }




}
